import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'

function stringify () {
  return qs.stringify()
}

// 常规配置
axios.defaults.baseURL = process.env.VUE_APP_API_PATH
axios.defaults.timeout = 120000
axios.defaults.withCredentials = true

// 相应拦截器
axios.interceptors.response.use(
  function (response) {
    const res = response.data
    // 下载文件是没有res.code值的，直接返回
    if (!res.code) {
      return res
    }
    // 正常请求，默认200为正确返回
    if (res.code != 200) { // 非正常返回
      Vue.prototype.$message({
        type: 'error',
        message: res.msg
      })
      return Promise.reject(new Error(res.message || '异常返回'))
    } else {
      return res
    }
  },
  function (error) {
    Vue.prototype.$message({
      type: 'error',
      message: '服务器响应失败'
    })
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

class BaseService {
  static get (url, params, config = {}) {
    if (params) {
      url += '?' + stringify(params)
    }
    return axios.get(url, config).then(response => {
      return response
    })
  }
  static post (url, data, config) {
    return axios.post(url, data, config).then(response => {
      return response
    })
  }
  static put (url, data, config = {}) {
    return axios.put(url, data, config).then(response => {
      return response
    })
  }
  static patch (url, data) {
    return axios.patch(url, data).then(response => {
      return response
    })
  }
  static del (url, params, config = {}) {
    if (params) {
      url += '?' + stringify(params)
    }
    return axios.delete(url, config).then(response => {
      return response
    })
  }
  static downLoadFile (fileName, options) {
    options.method = options.method || 'get'
    // 还会返回blob类型的数据
    options.responseType = 'blob'
    if (options.params) {
      options.url += '?' + stringify(options.params)
      delete options.params
    }
    return axios(options).then(response => {
      const blob = new Blob([response], {
        type: response['type']
      })
      let a = document.createElement('a')
      a.target = '_blank'
      a.href = URL.createObjectURL(blob)
      a.download = fileName
      a.click()
      a.remove()
      return {
        code: 200,
        message: '下载成功'
      }
    })
  }
}

function post (url, data, type) {
  return BaseService.post(url, data, type).then(response => response)
}

export {
  post
}
